package com.example.Servlet;

import com.example.Pojo.Member;
import com.example.Pojo.Price;
import com.example.Pojo.Profit;
import com.example.dao.impl.AdminManagerImpl;
import com.example.dao.impl.OperationDaoImpl;
import com.example.dao.impl.UserDaoImpl;
import com.google.gson.Gson;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

public class Dispose extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");
        if ("mreduce".equals(action)){
            //减少操作
            System.out.println("reduce");
            mreduce(req,resp);
        }else if("delete".equals(action)){
            System.out.println("delete");
            deleteUser(req,resp);
        }else if("search".equals(action)) {
            System.out.println("查询客户...");
            searchMeb(req,resp);
        }else{
            System.out.println("无操作...");

        }
    }

    private void searchMeb(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException{
        String tellphone = req.getParameter("tellphone");
        resp.setContentType("html/text;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        Member member = new UserDaoImpl().getMember(tellphone);
        String json = gson.toJson(member);
        out.println(json);
    }

    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException{
        String tellphone = req.getParameter("tellphone");
        String operation = "";        //当前操作
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());   //获得当前时间
        Member member = new UserDaoImpl().getMember(tellphone);
        operation = "用户"+member.getUsername()+"已被删除";
        if (member != null && new UserDaoImpl().deleteUser(tellphone) > 0 && new UserDaoImpl().insertOperation(member,operation,time) > 0 ){
            if (new OperationDaoImpl().countOperation() >14 && new OperationDaoImpl().deleteOne() >0){
                System.out.println("删除成功!");
            }else {
                System.out.println("删除成功，但数据处理异常");
            }
        }else {
            System.out.println("删除失败");
        }
    }

    private void mreduce(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String type = req.getParameter("type");     //减少的理发项目类型
        String tellphone = req.getParameter("tellphone");   //减少操作的目标客户电话
        int times = Integer.valueOf(req.getParameter("times"));   //总次数（没必要）
        String lev = req.getParameter("level");     //获取理发师的等级
        String[] master = lev.split(":");   //得到理发师的名字
        Member member = new UserDaoImpl().getMember(tellphone);     //得到该电话对应的顾客 能遍历出来就一定存在于数据库
        String op_type="";
        String options = "次数-1";    //操作内容
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());       //当前操作时间
        //得到操作的内容       得到操作的时间   理发师等级
        switch (type) {
            case "haircut":
                op_type = "剪发";
                break;
            case "perm":
                op_type = "烫发";
                break;
            case "wash_protect":
                op_type = "护理";
                break;
            case "hairroot":
                op_type = "补发根";
                break;
            case "colour":
                op_type = "染发";
                break;
            case "wash":
                op_type = "洗发";
                break;
            case "black":
                op_type = "黑油";
                break;
        }
        options = op_type+options+",理发师"+lev;
        //执行消费
        double cost = profit(type,master[0],master[1].substring(0,1));
        double consume = Double.valueOf(member.getConsume());
        double invest = Double.valueOf(member.getInvest());
        if (invest < cost){
            System.out.println("余额不足");
            writer.print("余额不足!");
        }else {
            consume+=cost;
            invest-=cost;
            if (new UserDaoImpl().updateCost(tellphone,String.valueOf(consume),String.valueOf(invest)) > 0 ){
                if (new UserDaoImpl().updateTimes(member,type,times-1,time) > 0 && new UserDaoImpl().insertOperation(member,options,time) > 0){
                    if (new OperationDaoImpl().countOperation() > 14 && new OperationDaoImpl().deleteOne() >0){
                        System.out.println("修改成功!");
                        writer.print("消费成功!");
                    }else {
                        System.out.println("修改成功，但数据处理异常");
                        writer.print("数据已修改,显示异常!");
                    }
                }else {
                    System.out.println("修改失败");
                }
            }else {
                System.out.println("消费失败");
                writer.print("出错啦~");
            }
        }
    }
    public void showAllUser(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        List<Member> memberList = new ArrayList<>();
        memberList = new UserDaoImpl().showAllUser();

        String json = gson.toJson(memberList);
        out.println(json);
    }
    //理发项目，理发师姓名，理发师等级
    public double profit(String type,String name,String lev){
        int pri = new AdminManagerImpl().findPrice(type);   //查询该理发项目的会员价格
        double TotalPrice = pri*(1-(0.1*Integer.valueOf(lev))); //理发师收益金额      按照几级理发师相应折扣计算最终金额
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());   //获取当前时间
        //按照用户名查找，如果找到则传给profit，如果没有则插入
        Profit profit = new AdminManagerImpl().selectProfitByName(name);
        //从数据库中未找到数据，执行插入
        if (profit == null){
            profit = new Profit();
            profit.setUsername(name);
            profit.setLevel(lev);
            profit.setPrice(TotalPrice);
            profit.setDate(date);
            if (new AdminManagerImpl().insertProfit(profit) >0){
                System.out.println("插入成功!");
                return TotalPrice;
            }else {
                System.out.println("插入失败!");
                return 0;
            }
        }else {
            //找到了就修改收益属性
            Double p = profit.getPrice();
            profit.setPrice(p+TotalPrice);
            if (new AdminManagerImpl().updateProfit(profit,name) > 0 ){
                System.out.println("更新数据!");
                return TotalPrice;
            }else
                System.out.println("更新失败!");
            return 0;
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
